package com.mediacloud.app.newsmodule.fragment.video.vod;


import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chinamcloud.collect.AcquisitionManager;
import com.donkingliang.consecutivescroller.ConsecutiveScrollerLayout;
import com.mediacloud.app.assembly.util.DrawableUtils;
import com.mediacloud.app.assembly.util.ImageKitKt;
import com.mediacloud.app.model.OnVideoPause;
import com.mediacloud.app.model.OnVideoPlayerPause;
import com.mediacloud.app.model.OnVideoPlayerPause2;
import com.mediacloud.app.model.eventbus.control.VideoDetailControl;
import com.mediacloud.app.model.eventbus.event.VideoAdEvent;
import com.mediacloud.app.model.eventbus.event.VideoDetailEvent;
import com.mediacloud.app.model.eventbus.mdoel.afpvideo.AppVideoAdItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.nav2.fragment.HqyNavFragment;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragment;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragmentX;
import com.mediacloud.app.newsmodule.fragment.recommend.RelatedListFragment;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.VideoAddressGet;
import com.mediacloud.app.newsmodule.utils.share.ShareWrap;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;
import com.utils.RxUtils;
import com.yoake.media.player.XPlayer;
import com.yoake.media.player.controller.component.ad.AdImageView;
import com.yoake.media.player.utils.OnPlayerActionListener;
import com.yoake.media.player.utils.XVideoBitRate;
import com.yoake.media.player.utils.XVideoItem;
import com.yoake.media.player.utils.XVideoSpeed;
import com.yoake.media.player.utils.interfaces.PendingPlayerChangeListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import xyz.doikki.videoplayer.player.BaseVideoView;
import xyz.doikki.videoplayer.player.VideoView;

/**
 * 列表播放器管理类
 * 用于资讯列表的
 * 有分享和文稿信息等
 */

public class VideoListPlayerUtil implements Runnable {
    public ArticleItem item;
    private Context context;
    private LifecycleOwner owner;
    public boolean playingShowAnim = true;
    public XListPlayer mPlayer;
    public XPlayer player;
    private Object mark = System.currentTimeMillis();
    private VideoDetailControl videoDetailControl;
    private View listView;
    public ViewGroup container;
    private View rootView;
    //  private AppVideoAdItem pauseAd;
    private View payTipView;
    private ShareWrap shareWrap;
    //用于横竖屏切换造成RecyclerView高度改变，会回调onScrolled()
    private boolean pendingPlayerChange = false;
    private boolean needPay;


    //只针对于 InfoFlowFragment  InfoFlowFragmentB
    public int mAutoCurPos = -1;
    public RecyclerView recyclerView;
    public RecyclerView.LayoutManager layoutManager;
    public RecyclerView.Adapter mRecyclerAdapter;
    public boolean isFirstAutoPlayer = true;
    public boolean isAutoPlayVideo = false;//是否走自动播放逻辑
    private boolean alpha1 = false;
    public Fragment fragment;
    public boolean isHandPlay = true;

    public Fragment getHqyNavFragment() {
        return fragment;
    }

    public void setHqyNavFragment(Fragment fragment) {
        this.fragment = fragment;
    }

    public boolean isPlayingOrPause() {
        if (mPlayer != null && player.isPlaying()) {
            return true;
        }
        return false;
    }

    public VideoListPlayerUtil(Context context, View listView,LifecycleOwner owner) {
        try {
            this.context = context;
            this.owner = owner;
            this.listView = listView;
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            videoDetailControl = new VideoDetailControl();
            initPlayer();
            setVideoPlayerListener();
            setListViewOnScrollListener();
            if (listView != null) {
                if (listView instanceof RecyclerView) {
                    recyclerView = (RecyclerView) listView;
                    layoutManager = recyclerView.getLayoutManager();
                    mRecyclerAdapter = recyclerView.getAdapter();
                }
            }
            player.addOnStateChangeListener(new BaseVideoView.OnStateChangeListener() {
                @Override
                public void onPlayerStateChanged(int playerState) {

                }

                @Override
                public void onPlayStateChanged(int playState) {

                    if (playingShowAnim && playState == VideoView.STATE_PLAYING && !alpha1) {
                        alpha1 = true;
                        ObjectAnimator animation = ObjectAnimator.ofFloat(mPlayer, "alpha", 0f, 1f);
                        animation.setDuration(600);
                        animation.setInterpolator(null);
                        animation.start();

                    }
                }
            });
            player.getBottomControl().setPendingPlayerChangeListener(new PendingPlayerChangeListener() {
                @Override
                public void onPendingPlayerStateChange() {
                    pendingPlayerChange = true;
                }
            });
        }catch (Exception e){

        }

    }

    private void initPlayer() {

        mPlayer = new XListPlayer(context,owner);
        player = mPlayer.getP();
        player.setOnTitleMoreClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (player.isFullScreen()) {
                        player.getController().getControllerInstance().hide();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                shareWrap.show(container);
            }
        });
    }

    /**
     * 设置播放器的容器
     *
     * @param container 播放器的容器
     */
    public void setPlayerContainer2(@NonNull View rootView, FrameLayout container, View logoView, ArticleItem item) {
        if (mPlayer == null)
            return;
        player.release();

        player.getPrepareView().mThumb.setVisibility(View.GONE);
        player.setPoster(ImageKitKt.buildUrl(3, item.getLogo()), ContextCompat.getDrawable(context, R.drawable.cctv7_loading_img));
        this.container = container;
        if (rootView.getParent() instanceof AbsListView || rootView.getParent() instanceof RecyclerView) {
            this.rootView = rootView;
        } else {
            ViewParent viewParent = null;
            do {
                if (viewParent == null)
                    viewParent = rootView.getParent();
                else {
                    viewParent = viewParent.getParent();
                }
                if (viewParent instanceof AbsListView || viewParent instanceof RecyclerView) {
                    break;
                }
                Log.v("VideoListPlayerUtil", "--->" + viewParent);
            } while (viewParent != null);

            this.rootView = ((ViewGroup) viewParent);
        }

        if (mPlayer.getParent() != null) {
            ViewGroup rl = (ViewGroup) mPlayer.getParent();
            rl.removeView(mPlayer);
        }
        if (payTipView != null && payTipView.getParent() != null) {
            ViewGroup rl = (ViewGroup) payTipView.getParent();
            rl.removeView(payTipView);
        }
        if (item.getType() == TypeX.NEWS.LIVE_VIDEO) {
            player.setPlayerType(XPlayer.VIDEO_LIVE);
        } else if (item.getType() == TypeX.NEWS.MICRO_DYNAMIC) {
            player.setPlayerType(XPlayer.VIDEO_VOD);
        } else {
            player.setPlayerType(XPlayer.VIDEO_VOD);
        }
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        player.getPrepareView().getPlayBtn().setVisibility(View.GONE);
        container.addView(mPlayer, 0, params);
        player.setAlpha(0.0f);

        ObjectAnimator animation0 = ObjectAnimator.ofFloat(logoView, "alpha", 0f);
        animation0.setDuration(500);
        animation0.setInterpolator(null);

        ObjectAnimator animation = ObjectAnimator.ofFloat(player, "alpha", 1f);
        animation.setDuration(500);
        animation.setInterpolator(null);
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                mPlayer.bringToFront();
                logoView.setAlpha(1f);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        AnimatorSet set = new AnimatorSet();
        set.playSequentially(animation0, animation);
        set.start();


        if (item.xVideoItem != null) {
            Log.w("AAXXCCXX", "使用列表数据");
            this.item = item;
            shareWrap.init(item, null);
            player.release();
            EventBus.getDefault().post(new OnVideoPause());
            player.addVideoItem(item.xVideoItem, true);
        }
    }


    /**
     * 设置播放器的容器
     *
     * @param container 播放器的容器
     */
    public void setPlayerContainer(@NonNull View rootView, ViewGroup container, View playIcon, boolean needPay, View.OnClickListener clickListener, ArticleItem item) {
        if (mPlayer == null)
            return;
        addViewHistory();
        player.release();
        // mPlayer.showControlerView();
        if (item.getType() == TypeX.NEWS.MICRO_DYNAMIC) {//这里不清楚之前的逻辑，只能针对微图文单独处理
            try {
                JSONObject jsonObject = new JSONObject(item.getVideo());
                String poster = jsonObject.optString("poster");
                player.getPrepareView().mThumb.setVisibility(View.GONE);
                player.setPoster(ImageKitKt.buildUrl(3, poster), null);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
//            String imgUrl = "";
//            if (item.getCmsCustomStyle() != null && item.getCmsCustomStyle().getImgPath().size() > 0) {
//                imgUrl = item.getCmsCustomStyle().getImgPath().get(0);
//            } else {
//                imgUrl = item.getLogo();
//            }
            player.getPrepareView().mThumb.setVisibility(View.GONE);
            player.setPoster(ImageKitKt.buildUrl(3, item.getLogo()), null);
            // mPlayer.setPoster(imgUrl, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.img_cut);

        }

        // mPlayer.showLoadingAnimation();
        this.container = container;

        if (rootView.getParent() instanceof AbsListView || rootView.getParent() instanceof RecyclerView) {
            this.rootView = rootView;
        } else {
            ViewParent viewParent = null;
            do {
                if (viewParent == null)
                    viewParent = rootView.getParent();
                else {
                    viewParent = viewParent.getParent();
                }
                if (viewParent instanceof AbsListView || viewParent instanceof RecyclerView) {
                    break;
                }
                Log.v("VideoListPlayerUtil", "--->" + viewParent);
            } while (viewParent != null);

            this.rootView = ((ViewGroup) viewParent);
        }

        if (mPlayer.getParent() != null) {
            ViewGroup rl = (ViewGroup) mPlayer.getParent();
            rl.removeView(mPlayer);
        }
        if (payTipView != null && payTipView.getParent() != null) {
            ViewGroup rl = (ViewGroup) payTipView.getParent();
            rl.removeView(payTipView);
        }
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        if (needPay) {
            if (payTipView == null) {
                ViewGroup parent = rootView instanceof ViewGroup ? (ViewGroup) rootView : container;
                payTipView = LayoutInflater.from(rootView.getContext()).inflate(R.layout.appfactory_tip_buy, parent, false);
                TextView tvGoDetail = payTipView.findViewById(R.id.playGoOn_detail);
                GradientDrawable gradientDrawable = new DrawableUtils.GradientDrawableBuilder()
                        .setRadius(40)
                        .setStroke(3, AppFactoryGlobalConfig.getAppServerConfigInfo(tvGoDetail.getContext()).getMainColor())
                        .setShape(GradientDrawable.RECTANGLE)
                        .create();
                tvGoDetail.setBackground(gradientDrawable);
            }
            if (clickListener != null) {
                payTipView.setOnClickListener(clickListener);
            }
            this.container.addView(payTipView, params);
        } else {
            player.getPrepareView().getPlayBtn().setVisibility(View.GONE);
            container.addView(mPlayer, params);
            mPlayer.setAlpha(0.0f);
            alpha1 = false;
            mPlayer.postDelayed(this, 2000);
        }
        this.needPay = needPay;
        // rootView.setOnClickListener(clickListener);
        if (item.getType() == TypeX.NEWS.LIVE_VIDEO) {
            player.setPlayerType(XPlayer.VIDEO_LIVE);
        } else if (item.getType() == TypeX.NEWS.MICRO_DYNAMIC) {
            player.setPlayerType(XPlayer.VIDEO_UNDEFINED);
            player.getTopView().setVisibility(View.GONE);
        } else {
            player.setPlayerType(XPlayer.VIDEO_VOD);
        }

        if (item.xVideoItem != null) {
            Log.w("AAXXCCXX", "使用列表数据");
            this.item = item;
            if (shareWrap == null) {
//                try {
//                    Activity activity = ActivityScanner.findActivity(container);
//                    shareWrap = new ShareWrap(activity, false);
//                    shareWrap.setShowFunction(true);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                shareWrap = new ShareWrap(container.getContext(), false);
                shareWrap.setShowFunction(true);
            }
            shareWrap.init(item, null);
            player.release();
            EventBus.getDefault().post(new OnVideoPause());
            player.addVideoItem(item.xVideoItem, true);
            //  doAcquisition(item);
        }
    }

    public void initPosition() {
        if (fragment != null) {
            if (fragment instanceof BaseNewsListFragment) {
                ((BaseNewsListFragment) fragment).curPosition = -1;
            } else if (fragment instanceof BaseNewsListFragmentX) {
                ((BaseNewsListFragmentX) fragment).curPosition = -1;
            } else if (fragment instanceof RelatedListFragment) {
                ((RelatedListFragment) fragment).curPosition = -1;
            }
        }
    }

    /**
     * 释放资源，移除父布局
     */
    public void stopPlay() {
        isHandPlay = true;
        addViewHistory();
        initPosition();
        mAutoCurPos = -1;
        if (mPlayer != null) {
            player.release();
        }
        if (mPlayer != null && mPlayer.getParent() != null) {
            ViewGroup rl = (ViewGroup) mPlayer.getParent();
            rl.removeView(mPlayer);
        }
        if (payTipView != null && payTipView.getParent() != null) {
            ViewGroup rl = (ViewGroup) payTipView.getParent();
            rl.removeView(payTipView);
        }
    }

    public void addViewHistory() {
       /* if (item != null && mPlayer != null && mPlayer.getP() != null) {
            long position = player.getCurrentPosition();
            VideoPlayHistory history = null;
            CollectionUtils.ReadNewsItem readNewsItem = CollectionUtils.getReadItem(context, item);
            if (readNewsItem != null) {
                ArticleItem readArticleItem = ArticleItem.parse(readNewsItem.newsContent);
                history = VideoPlayHistory.parse("" + readArticleItem.extendField);
            } else {
                history = new VideoPlayHistory();
            }
            history.date = DateParse.getNowDate(null);
            if (position > 0)
                history.time = position;
            item.extendField = history.toString();
            item.setParentId(String.valueOf(item.getCatalogId()));
            CollectionUtils.addReadRecord(context, item);
        }*/

    }

    /**
     * 监听ListView 滚动
     */
    private void setListViewOnScrollListener() {
        if (listView instanceof AbsListView) {
            ((AbsListView) listView).setOnScrollListener(new AbsListView.OnScrollListener() {
                int mScrollState;

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    mScrollState = scrollState;
                    Log.w("VideoListPlayerUtil", "AbsListView-onScrollStateChanged：" + mScrollState);
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    if (player.isFullScreen()) return;
                    if (pendingPlayerChange) {
                        pendingPlayerChange = false;
                        return;
                    }
                    Log.w("VideoListPlayerUtil", "AbsListView-onScroll：" + firstVisibleItem + "," + visibleItemCount + "," + totalItemCount);
                    if (container==null){
                        return;
                    }
                    if (!container.isShown() || !container.getLocalVisibleRect(new Rect(container.getLeft(), container.getTop(), listView.getMeasuredWidth(), listView.getMeasuredHeight())))
                        player.pause();
                    if (rootView == null || listView == null || mScrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE)
                        return;
                    if (!container.isShown() || !container.getLocalVisibleRect(new Rect(rootView.getLeft(), rootView.getTop(), listView.getMeasuredWidth(), listView.getMeasuredHeight()))) {
                        stopPlay();
                    }
                   /* if (rootView.getBottom() <= 20 || rootView.getTop() >= listView.getHeight() - 40) {
                        stopPlay();
                    }*/
                }
            });
        } else if (listView instanceof RecyclerView) {
            ((RecyclerView) listView).addOnScrollListener(new RecyclerView.OnScrollListener() {
                int mScrollState;

                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    mScrollState = newState;
                    Log.w("VideoListPlayerUtil", "RecyclerView-onScrollStateChanged:" + mScrollState);
                    if (isAutoPlayVideo) {
                        try {
                            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                                if (layoutManager instanceof GridLayoutManager) {
                                    VideoListPlayerUtilToolKt.onScrollReleaseAllVideos(VideoListPlayerUtil.this,
                                            ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition(),
                                            ((GridLayoutManager) layoutManager).findLastVisibleItemPosition(),
                                            0.2f);


                                    VideoListPlayerUtilToolKt.onScrollPlayVideo(
                                            VideoListPlayerUtil.this,
                                            ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition(),
                                            ((GridLayoutManager) layoutManager).findLastVisibleItemPosition());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    isAutoPlayVideo = MMKV.defaultMMKV().getBoolean(XKey.AUTO_PLAY,false);

                    if (isAutoPlayVideo) {
                        try {
                            if (dy != 0) {
                                VideoListPlayerUtilToolKt.onScrollReleaseAllVideos(VideoListPlayerUtil.this,
                                        ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition(),
                                        ((GridLayoutManager) layoutManager).findLastVisibleItemPosition(),
                                        0.8f);
                            } else {
                                if (isFirstAutoPlayer) {
                                    if (layoutManager instanceof GridLayoutManager) {
                                        VideoListPlayerUtilToolKt.onScrollPlayVideo(
                                                VideoListPlayerUtil.this,
                                                ((GridLayoutManager) layoutManager).findFirstVisibleItemPosition(),
                                                ((GridLayoutManager) layoutManager).findLastVisibleItemPosition());
                                    }
                                    isFirstAutoPlayer = false;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (rootView == null || listView == null || mScrollState == RecyclerView.SCROLL_STATE_IDLE)
                            return;
                    /*if (rootView.getBottom() <= 20 || rootView.getTop() >= listView.getHeight() - 40) {
                        stopPlay();
                    }*/
                        if (!container.isShown() || !container.getLocalVisibleRect(new Rect(rootView.getLeft(), rootView.getTop(), listView.getMeasuredWidth(), listView.getMeasuredHeight()))) {
                            stopPlay();
                        }
                    }
                }
            });
        } else if (listView instanceof ConsecutiveScrollerLayout) {

            ((ConsecutiveScrollerLayout) listView).setOnVerticalScrollChangeListener(new ConsecutiveScrollerLayout.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollY, int oldScrollY, int scrollState) {
                    if (scrollState == ConsecutiveScrollerLayout.SCROLL_STATE_IDLE) return;
                    if (rootView!=null){
                        if (!container.isShown() || !container.getLocalVisibleRect(new Rect(rootView.getLeft(), rootView.getTop(), listView.getMeasuredWidth(), listView.getMeasuredHeight()))) {
                            stopPlay();
                        }
                    }else {
                        if (!container.isShown()) {
                            stopPlay();
                        }
                    }

                }
            });
        }

    }


    long currentItemId;

    public void setVideoDetail(String navigate_id, ArticleItem item) {
        if (fragment != null) {
            if (fragment.getActivity() == null || fragment.getActivity().isFinishing() || fragment.getActivity().isDestroyed()
                    || fragment.isDetached()
                    || fragment.isRemoving()
                    || ((fragment instanceof HqyNavFragment) && !((HqyNavFragment) fragment).hadChoosed)) {
                return;
            }
        }
        if (needPay) {
            return;
        }
        UserInfo info = UserInfo.getUserInfo(context);
        currentItemId = item.getId();
        videoDetailControl.getVideoDetail("" + item.getId(), navigate_id, info.getUserid(), mark);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciveVideoDetail(VideoDetailEvent<List<AppVideoAdItem>, ArticleItemReciver> event) {

        if (fragment != null) {
            if (fragment.getActivity() == null || fragment.getActivity().isFinishing() || fragment.getActivity().isDestroyed()
                    || fragment.isDetached()
                    || fragment.isRemoving()
                    || ((fragment instanceof HqyNavFragment) && !((HqyNavFragment) fragment).hadChoosed)) {
                return;
            }
        }
        initPosition();
        if (event.getType() != VideoDetailEvent.ResultDetail || event.getData().otherData != mark)
            return;
        setVideoData(event.getData());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPause(OnVideoPlayerPause pause) {

        initPosition();
        if (mPlayer != null) {
            player.release();
            if (mPlayer.getParent() != null) {
                ViewGroup parent = (ViewGroup) mPlayer.getParent();
                parent.removeView(mPlayer);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPause(OnVideoPlayerPause2 pause) {

        initPosition();
        if (mPlayer != null) {
            player.release();
            if (mPlayer.getParent() != null) {
                ViewGroup parent = (ViewGroup) player.getParent();
                parent.removeView(mPlayer);
            }
        }
    }

//    private void setBufferAd(List<AppVideoAdItem> adDetail) {
//        if (adDetail != null && adDetail.size() > 0) {
//            player.addAdstartItem(adDetail);
//            player.setAdStartTotalTime();
//            player.toggleFullScreenEnable(true);
//        } else
//            player.toggleFullScreenEnable(false);
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reciceVideoAdData(VideoAdEvent<List<AppVideoAdItem>> event) {
        if (event.mark != mark || event.getData() == null || event.getData().size() == 0)
            return;
//        if (event.getType() == VideoAdEvent.PauseAd) {
//            setPauseAd(event.getData());
//        } else if (event.getType() == VideoAdEvent.EndAd) {
//            setEndAd(event.getData());
//        }
    }

//    private void setPauseAd(List<AppVideoAdItem> adDetail) {
//        pauseAd = adDetail != null && adDetail.size() > 0 ? adDetail.get(0) : null;
//    }
//
//    private void setEndAd(List<AppVideoAdItem> adDetail) {
//        player.clearAdEndItem();
//        player.addAdEndItem(adDetail);
//        player.setAdEndTotalTime();
//    }

    /**
     * 数据采集
     */
    private void doAcquisition(ArticleItem item) {
        if (item != null) {
            AcquisitionManager m = AcquisitionManager.getInstance();
            final UserInfo user = UserInfo.getUserInfo(context);

            List<XVideoItem> objs = player.getVideoItems();
            if (objs != null && !objs.isEmpty()) {
                List<XVideoBitRate> items = objs.get(0).getBitRates();
                if (items != null && !items.isEmpty()) {
                    String url = items.get(0).getPath();
                    m.playVideo(user, item.getId() + "", DomainUtil.getDomain(item.getUrl()), item.getUrl(),
                            item.getTitle(), item.getContent(), url);
                }
            }
        }

    }


    public void setVideoData(ArticleItemReciver data) {
        if (currentItemId != data.articleItem.getId()) return;
//        if (pendingRootView != null) {
//            setPlayerContainer(pendingRootView, pendingContainer, pendingNeedPay, pendingClickListener, pendingItem);
//        }
        if (data.state && data.articleItem != null) {
            item = data.articleItem;
            if (shareWrap == null) {
                try {
                    //   Activity activity = ActivityScanner.findActivity(container);
                    shareWrap = new ShareWrap(container.getContext(), false);
                    shareWrap.setShowFunction(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            shareWrap.init(item, null);
            player.release();
            try {
                JSONObject video = new JSONObject(item.getVideo());
                JSONArray tsAddress = VideoAddressGet.getAddress(video);
                XVideoItem videoPlayObj = new XVideoItem(item.getTitle());
                String cdnEncypt = video.optString("cdnConfigEncrypt");
                videoPlayObj.setCdnIv(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                videoPlayObj.setCdnKey(AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key);
                for (int i = 0; i < tsAddress.length(); i++) {
                    JSONObject line = tsAddress.optJSONObject(i);
                    XVideoBitRate lineItem = new XVideoBitRate();
                    lineItem.setPath(line.optString("url"));
                    lineItem.setTitle(line.optString("title"));
                    lineItem.setCdnEncypt(cdnEncypt);
                    videoPlayObj.getBitRates().add(lineItem);
                }
                EventBus.getDefault().post(new OnVideoPause());
                player.addVideoItemReverse(videoPlayObj, "源码", true);
                //    doAcquisition(item);
            } catch (Exception e) {
                e.printStackTrace();
                player.onExternalError();
            }
        } else {
            player.onExternalError();
        }

    }
public RxUtils.CallBack<Integer> playStateCallBack;
    /**
     * 设置播放器各种监听
     */
    private void setVideoPlayerListener() {

//        player.setAdCliclkListenter(new AdCliclkListenter() {
//
//            @Override
//            public void OnAdCliclkListenter(String LinkUrl, boolean isvideo, AdItem adItem) {
//                if (TextUtils.isEmpty(LinkUrl))
//                    return;
//                ArticleItem articleItem = new ArticleItem();
//                articleItem.setLinkNews(false);
//                articleItem.setUrl(LinkUrl);
//                articleItem.setTitle(context.getString(R.string.adtitile));
//                AppVideoAdItem videoAdItem = (AppVideoAdItem) adItem;
//                if (videoAdItem != null) {
//                    DataInvokeUtil.invokeAfpStatics(videoAdItem.clickTracking);
//                }
//                NewsItemClickUtils.OpenItemNewsHandle(context, TypeX.NEWS.LINK, articleItem, null, NeedTokenType.Unnecessary, false, false);
//            }
//        });
//        player.setAdPlayListener(new AdPlayListener() {
//            @Override
//            public void adComplete(boolean isLast, ADType adType) {
//                if (isLast && adType == ADType.START_AD) {
//                    player.setvideoQualityTitleViseble(View.VISIBLE);
//                }
//                if (isLast && adType == ADType.END_AD) {
//                    player.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            stopPlay();
//                        }
//                    }, 200);
//                }
//            }
//        });

        player.addOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {
                if(playerState == VideoView.STATE_PAUSED){

                }


                if (playerState == VideoView.PLAYER_FULL_SCREEN) {

                }
            }

            @Override
            public void onPlayStateChanged(int playState) {
                if (playStateCallBack!=null){
                    playStateCallBack.call(playState,playState);
                }
                if (playState == VideoView.STATE_PAUSED) {

                } else if (playState == VideoView.STATE_PLAYING) {

                } else if (playState == VideoView.STATE_PLAYBACK_COMPLETED) {
                    stopPlay();
                }

            }
        });
        player.setOnPlayerActionListener(new OnPlayerActionListener() {
            @Override
            public void onProjectionScreen() {
                //投屏回调
            }

            @Override
            public void onSpeedChange(@Nullable XVideoSpeed before, @NonNull XVideoSpeed after) {

            }

            @Override
            public void onBitRateChange(@Nullable XVideoBitRate before, @NonNull XVideoBitRate after) {

            }

            @Override
            public void onDamuSwitch(boolean isOpen) {
                if (isOpen){

                }else{

                }
            }

            @Override
            public void onPlayerStateChanged(int playerState) {
                boolean isFullScreen = playerState == VideoView.PLAYER_FULL_SCREEN;
                if (isFullScreen){


                }else {

                }

            }

            @Override
            public void onSeekTo(boolean isForward) {
                if (isForward){


                }else{

                }
            }
        });
        //       player.setOnPlayerListener(new VideoPlayerListenerImpl() {
//            @Override
//            public void onpause(int currentMediaIndex) {
//                super.onpause(currentMediaIndex);
//                if (pauseAd != null)
//                    player.showAdPausevertiseView(pauseAd);
//                ReportManager.getInstance().pause_play_video(item.getVid(),item.getType()+"",item.getId()+"",item.getTitle(),
//                        item.getId()+"",item.getTitle(),item.getReferName(),item.getAuthor(),item.getAuthor(),currentMediaIndex+"");
//            }
//
//            @Override
//            public void oncomplete(int currentMediaIndex) {
//                super.oncomplete(currentMediaIndex);
//                if (mPlayer.isFullScreen()) {
//                    player.toggleFullScreen();
//                }
//                if (mPlayer.adendList.size() == 0)
//                    player.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            stopPlay();
//                        }
//                    }, 0);
//            }
//
//            @Override
//            public void onVideoComletionAd() {
//                super.onVideoComletionAd();
//            }
//
//            @Override
//            public void ontoggleFullScreen(int currentMediaIndex, boolean isFullScreen) {
//                super.ontoggleFullScreen(currentMediaIndex, isFullScreen);
//                if (isFullScreen) {
//                    ViewGroup rootView = ViewUtils.searchTintContextHostActivity(context).findViewById(android.R.id.content);
//                    ViewGroup parent = (ViewGroup) player.getParent();
//                    FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
//                    parent.removeView(mPlayer);
//                    rootView.addView(mPlayer, frameLayoutParams);
//                    ReportManager.getInstance().fullscreen_play_video(item.getVid(),item.getType()+"",item.getId()+"",item.getTitle(),
//                            item.getId()+"",item.getTitle(),item.getReferName(),item.getAuthor(),item.getAuthor(),currentMediaIndex+"");
//                } else {
//                    if (mPlayer != null && player.getParent() != null) {
//                        ViewGroup parent = (ViewGroup) player.getParent();
//                        parent.removeView(mPlayer);
//                    }
//                    if (mPlayer != null) {
//                        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
//                        container.addView(mPlayer, params);
//                    }
//                }
//            }
//
//            @Override
//            public void onPrepared(int currentMediaIndex) {
//                super.onPrepared(currentMediaIndex);
//                player.toggleFullScreenEnable(true);
//                try {
//
//                    String[] times = item.getProp4().split(":");
//                    int hours, min, sec;
//                    hours = Integer.valueOf("" + times[0]);
//                    min = Integer.valueOf("" + times[1]);
//                    sec = Integer.valueOf("" + times[2]);
//                    int total = hours * 60 * 60;
//                    total += min * 60;
//                    total += sec;
//                    if (total > 0)
//                        player.setConfigDuration(total);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                ReportManager.getInstance().play_video(item.getVid(),item.getType()+"",item.getId()+"",item.getTitle(),
//                        item.getId()+"",item.getTitle(),item.getReferName(),item.getAuthor(),item.getAuthor());
//            }
//
//        });


    }

    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (player != null) {
            player.getConnectivityEngine().unregisterNetworkChangeListener();
            AdImageView adImageView = player.getAdImageView();
            if (adImageView != null) {
                adImageView.cancelCountDown();
            }
            if (player.getCdnUrl() != null) {
                player.getPreloadManager().removePreloadTask(player.getCdnUrl());
            }
            if (player.getVRLibrary() != null) {
                player.getVRLibrary().onDestroy();
            }
            if (context instanceof LifecycleOwner) {
                ((LifecycleOwner) context).getLifecycle().removeObserver(player);
            }
        }

        stopPlay();
        fragment = null;
        context = null;
    }

    public XPlayer getPlayer() {
        return player;
    }

    @Override
    public void run() {
        if (!alpha1) {
            alpha1 = true;
            if (mPlayer != null) {
                mPlayer.setAlpha(1f);
            }
        }
    }
}